<template>
  <view class="register-container">
    <view class="form-container">
      <text class="register-title">注册</text>
      <view class="input-group">
        <wd-input type="text" v-model="form.username" placeholder="请输入用户名" clearable />
      </view>
      <view class="input-group">
        <wd-input type="password" v-model="form.password" placeholder="请输入密码" show-password clearable />
      </view>
      <view class="btn-row">
        <text class="back-link" @click="goLogin">返回登入</text>
        <wd-button type="primary" :loading="loading" @click="handleRegister" class="register-btn">注册</wd-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { request, BASE_URL } from '@/Requset/request'

const form = reactive({
  username: '',
  password: ''
})
const loading = ref(false)

async function handleRegister() {
  if (!form.username.trim()) {
    uni.showToast({ title: '请输入用户名', icon: 'none' })
    return
  }
  if (!form.password) {
    uni.showToast({ title: '请输入密码', icon: 'none' })
    return
  }
  loading.value = true
  try {
    const response = await request({
      url: BASE_URL + 'api/register',
      method: 'POST',
      data: {
        username: form.username,
        password: form.password
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      }
    })
    const res = (response as any).data
    if (res && res.status === 0) {
      uni.showToast({ title: res.message || '注册成功', icon: 'success' })
      setTimeout(() => {
        uni.reLaunch({ url: '/pages/Login/Login' })
      }, 1000)
    } else {
      uni.showToast({ title: res.message || '注册失败', icon: 'none' })
    }
  } catch (e: any) {
    uni.showToast({ title: e.message || '请求失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

function goLogin() {
  uni.reLaunch({ url: '/pages/Login/Login' })
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 40rpx;
}
.form-container {
  width: 100%;
  max-width: 600rpx;
  background: #fff;
  border-radius: 16rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
}
.register-title {
  display: block;
  text-align: center;
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 60rpx;
  color: #333;
}
.input-group {
  margin-bottom: 40rpx;
}
.btn-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30rpx;
}
.back-link {
  color: #999;
  font-size: 26rpx;
  cursor: pointer;
  flex: 1;
  text-align: left;
}
.register-btn {
  flex: 1;
  margin-left: 20rpx;
}
</style>